import { ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Checkbox,
  Select,
  Radio,
  DatePicker,
  message,
  Space,
} from "antd";
import { connect } from "umi";
import type { GetProps } from "antd";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useState, useRef } from "react";

const { TextArea } = Input;
import dayjs from "dayjs";
import { PlusOutlined } from "@ant-design/icons";
import Https from "@/utils/Https";
import { getItem } from "@/utils/localstorage";

const Page = (props) => {
  const { RangePicker } = DatePicker;
  const { dispatch, submitLoading, venueArr } = props;
  const actionRef = useRef();
  const [open, setOpen] = useState(false);
  const [row, setRow] = useState(null);
  const [allStaff, setAllStaff] = useState([]);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;

  useEffect(() => {
    dispatch({
      type: `${namespace}/allStaffListReq`,
      params: {
        venueId: getItem("venueInfo").id,
      },
      callback: (res) => {
        setAllStaff(res);
      },
    });
  }, []);

  const disabledDate: RangePickerProps["disabledDate"] = (current) => {
    return current && current < dayjs().subtract(1, "days");
  };
  const editInfo = (params) => {
    setRow(params);
    let {
      id,
      staffId,
      venueId,
      staffName,
      startTime,
      endTime,
      remark,
      venueName,
    } = params;
    form.setFieldsValue({
      id,
      staffId,
      venueId,
      staffName,
      venueName,
      rangeTime: [dayjs(startTime), dayjs(endTime)],
      remark,
    });
    setOpen(true);
  };
  const deleteItem = (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };

  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        form.setFieldsValue({ ...res });
        setOpen(true);
      },
    });
  };

  const onChange = (e) => {
    const venueId = e.target.value;
    dispatch({
      type: `${namespace}/allStaffListReq`,
      params: {
        venueId,
      },
      callback: (res) => {
        setAllStaff(res);
      },
    });
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (id, record) => {
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => deleteItem({ id: record.id })}>
            删除
          </Button>
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      let params;
      let { rangeTime } = res;
      if (row) {
        params = {
          ...res,
          id: res.id,
          //venueId: res.venueId,
          staffIds: res.staffId,
          startTime: dayjs(rangeTime[0]).format("YYYY-MM-DD HH:mm:00"),
          endTime: dayjs(rangeTime[1]).format("YYYY-MM-DD HH:mm:00"),
        };
      } else {
        params = {
          ...res,
          staffIds: res.staffId,
          startTime: dayjs(rangeTime[0]).format("YYYY-MM-DD HH:mm:00"),
          endTime: dayjs(rangeTime[1]).format("YYYY-MM-DD HH:mm:00"),
        };
      }
      delete params.rangeTime;
      let url = params.id
        ? "/holiday/updateSingleHoliday"
        : "/holiday/staffHolidayConfig";
      setLoading(true);
      let result: any = await Https.post(url, params, true);
      setLoading(false);
      if (result.code == 200) {
        message.success("操作成功");
        setOpen(false);
        actionRef.current && actionRef.current?.reload();
      } else {
        message.error(result.msg);
      }
    }
  };

  return (
    <>
      <ProTable
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setRow(null);
              form.resetFields();
              setOpen(true);
            }}
          >
            新增员工休假
          </Button>,
        ]}
        pagination={{
          showSizeChanger: true,
        }}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        columns={calcColumns({ operate })}
      />
      <Modal
        open={open}
        title={row?.id ? "编辑员工放假" : "新增员工放假"}
        forceRender
        width="40%"
        onCancel={() => setOpen(!open)}
        onOk={() => {
          submitForm();
        }}
        confirmLoading={loading}
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="所属场馆"
            name="venueId"
            hidden={row?.id}
            rules={[{ required: true, message: "请选择所属场馆" }]}
          >
            <Radio.Group onChange={onChange}>
              {venueArr.map((v) => (
                <Radio value={v.id}>{v.venueName}</Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          {row?.id && (
            <Form.Item label="所属场馆" name="venueName" required={true}>
              <span>{form.getFieldValue("venueName")}</span>
            </Form.Item>
          )} */}
          {row?.id && (
            <Form.Item label="员工姓名" name="staffName" required={true}>
              <span>{form.getFieldValue("staffName")}</span>
            </Form.Item>
          )}
          <Form.Item
            label="选择员工"
            name="staffId"
            hidden={row?.id}
            rules={[{ required: true }]}
          >
            <Select>
              {allStaff.map((v) => (
                <Select.Option value={v.userId}>{v.nickName}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="放假时间"
            name="rangeTime"
            rules={[{ required: true, message: "请选择放假时间" }]}
          >
            <RangePicker
              disabledDate={disabledDate}
              showTime={{
                hideDisabledOptions: true,
              }}
              minuteStep={15}
              format="YYYY-MM-DD HH:mm"
            />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <TextArea
              showCount
              rows={4}
              maxLength={300}
              placeholder="请输入备注"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
